package com.wujunshen.thread.jmm;

import org.apache.commons.lang3.exception.ExceptionUtils;

import lombok.extern.slf4j.Slf4j;

/**
 * @author frank woo(吴峻申) <br>
 *     email:<a href="mailto:frank_wjs@hotmail.com">frank_wjs@hotmail.com</a> <br>
 * @date 2020/7/26 01:53<br>
 */
@Slf4j
public class FinalThisEscape {
  static FinalThisEscape obj;
  /** final常量会保证在构造器内完成初始化（但是仅限于未发生this逃逸的情况下，具体见多线程对final保证可见性的实现） */
  final int x;

  /** 错误的构造方法 */
  public FinalThisEscape() {
    x = 3;
    // this引用逃逸
    obj = new FinalThisEscape();
  }

  public static void main(String[] args) {
    Thread thread =
        new Thread(
            () -> {
              FinalThisEscape finalThisEscape = obj;

              try {
                log.info("{}", finalThisEscape.x);
              } catch (NullPointerException e) {
                log.error("final变量x未被初始化,{}", ExceptionUtils.getStackTrace(e));
              }
            });
    thread.start();
  }
}
